package com.xudow.app.ui.task;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.activeshare.edu.ucenter.common.messages.cart.CartMessage;
import com.activeshare.edu.ucenter.common.messages.course.CourseDetailMessage;
import com.activeshare.edu.ucenter.common.messages.order.OrderListMessage;
import com.activeshare.edu.ucenter.models.cart.CartItem;
import com.activeshare.edu.ucenter.models.cart.ShoppingCartWithCourse;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.activeshare.edu.ucenter.models.order.AgencyOrderDetail;
import com.google.gson.Gson;
import com.xudow.app.Config;
import com.xudow.app.XApplication;
import com.xudow.app.model.CartModle;
import com.xudow.app.model.Coures;
import com.xudow.app.newui.bean.LsCatMessage;
import com.xudow.app.util.FileUtils;
import com.xudow.app.util.rest.XRestTemplate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 获取课程列表Task
 *
 * @author lukecheng
 */
public class GetCarListTask extends AsyncTask<HashMap<String, String>, Void, Void> {
    private static final String TAG = makeLogTag(GetCarListTask.class);

    private static final String CAR_LIST_URL = Config.BASE_URL + Config.SHOPPING_CART_LIST_URL;

    public static final int SUCCESS = 0;
    public static final int ERROR = 1;

    private Context context;
    private Handler handler;

    public GetCarListTask(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
    }

    private void sendErrorMessage(String msg) {
        android.os.Message message = new android.os.Message();
        message.what = ERROR;

        if (null != msg) {
            Bundle data = new Bundle();
            data.putString("errMessage", msg);
            message.setData(data);
        }

        handler.sendMessage(message);
    }

    /**
     * 更改使用message.obj传递数据
      * @param carlist
     */
    private void sendSuccessMessage(List<LsCatMessage.CartItemsEntity> carlist) {
        android.os.Message message = new android.os.Message();
        message.what = SUCCESS;
        message.obj=carlist;
        handler.sendMessage(message);
    }

    @Override
    protected Void doInBackground(HashMap<String, String>... parameters) {
      XApplication application = (XApplication) context.getApplicationContext();

        XRestTemplate restTemplate = new XRestTemplate(application.getCookieStore(), context);
        // restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());


        String string = restTemplate.getForObject(CAR_LIST_URL,
                   String.class);
        Log.i("GetCarListTask", "string>>> "+string);
        LsCatMessage result=new Gson().fromJson(string, LsCatMessage.class);
           Log.i("GetCarListTask", "result>>> "+result);
        if (result != null) {
                /*Log.e(TAG, "carlist: "+result );
                try {
                    FileUtils.writeFile(result,new File(context.getCacheDir().getAbsolutePath(),"cartlist.txt"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                sendSuccessMessage(getData(result));*/
                if (result.getResult().equals("0")){
                    sendSuccessMessage(result.getCartItems());
                }else if (result.getResult().equals("1")){
                    sendErrorMessage(result.getErrorMessage());
                }
            } else {
                sendErrorMessage(null);
            }
        return null;
    }

    /**
     * 封装carList对象
     * @param result
     */
    private List getData(String result) {
        try {
            JSONObject obj=new JSONObject(result);
            JSONArray arr=obj.getJSONArray("cartItems");
            Set<CartModle> set=new HashSet<CartModle>();
            List<Coures> list=new ArrayList<Coures>();
            for(int i=0;i<arr.length();i++){
                CartModle cm=new CartModle();
                Coures coures=new Coures();
                JSONObject jobj= arr.getJSONObject(i);
                JSONObject json=jobj.getJSONObject("courseWithOtherInfo");
                coures.courId= json.getLong("id");
                coures.type=json.getInt("type");

                coures.schoolId= json.optLong("schoolId");
                coures.teacher=json.getString("teacher");
                coures.courName=json.getString("name");
                coures.agencyName = json.optString("agencyName");
                coures.school = json.optString("schoolName");
                coures.userSendSchoolName = json.optString("userSendSchoolName");
                coures.userSendSchoolAddress = json.optString("userSendSchoolAddress");
                coures.actual_price = json.getDouble("actualPrice");
                coures.price = json.getDouble("coursePrice");
                coures.courImag = json.getString("thumbnail");

                coures.studentId = jobj.optLong("studentId");

                coures.studentName = jobj.getString("studentName");

                coures.itemId=jobj.getLong("id");
                cm.schoolId =coures.schoolId;
                cm.itemId=jobj.getLong("id");
                cm.agencyNmae = coures.agencyName;
                cm.userSendSchoolName=coures.userSendSchoolName;
                cm.userSendAddress=coures.userSendSchoolAddress;
                cm.teacher=coures.teacher;
                cm.schoolName = coures.school;
                set.add(cm);
                list.add(coures);
            }
            for (CartModle mc : set) {
                mc.couresList=new ArrayList<Coures>();
                for (Coures c : list) {
                    if (null!=mc.schoolId&&mc.schoolId==c.schoolId){
                        mc.couresList.add(c);
                    }else if (null!=mc.sendlocid&&mc.sendlocid==c.sendlocid){
                        mc.couresList.add(c);
                    }
                }
            }
            List<CartModle> cmlist=new ArrayList<CartModle>(set);
            return cmlist;
        } catch (JSONException e) {
            LOGE("jsonexception",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
